<template>
  <div>
    <a-form :model="formState" ref="userCompany">
      <a-form-item name="companyIds">
        <a-transfer :dataSource="companyList" v-model="formState.companyIds" :listStyle="{ width: '45%', height: '480px' }" :titles="[' 可选企业', ' 已选企业']" :render="(item) => item.title" :target-keys="formState.companyIds" @change="handleTransferChange" filterable> </a-transfer>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" name="UserCompany" setup>
import { ref, reactive } from 'vue'
import { getAuthCompanyList, setUserCompany } from '@/views/sys/user/data/user.api'
const userCompany = ref()
const companyList = ref()
const userId = ref()
const formState = reactive({
  companyIds: [],
})

/**
 * 设置数据
 * @param data
 */
async function setData(data) {
  userId.value = data.record.userId
  getAuthCompanyList({
    organizationId: data.record.organizationId,
    userId: userId.value,
  }).then((data) => {
    data.companyList.map((item) => {
      item.key = item.companyId
      item.title = item.companyName
    })
    companyList.value = data.companyList
    formState.companyIds = data.companyIds
  })
}

/**
 * 穿梭框change
 * @param targetKeys
 * @param direction
 * @param moveKeys
 */
function handleTransferChange(targetKeys, direction, moveKeys) {
  formState.companyIds = targetKeys
}

/**
 * 提交已分配企业
 */
async function handleSubmit(drawerEmit) {
  userCompany.value.validate().then(() => {
    setUserCompany({
      userId: userId.value,
      companyIds: formState.companyIds.join(','),
    })
  })
}

/**
 * 暴露给父组件调用的方法
 */
defineExpose({
  setData,
  handleSubmit,
})
</script>
